package cn.com.ddapp.ddm.util;

import android.os.Handler;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/7/19 0019.
 */
public class JsonHttpNet {
    private static OkHttpClient okHttpClient;
    static {
        okHttpClient = new OkHttpClient();
    }
    //定义一个线程池
    public static ExecutorService executor = Executors.newFixedThreadPool(5);
    private static Handler handler = new Handler();

    public interface HttpCallbackListener {
        void onFinish(String response);

        void onError(Exception e);
    }

    public static void dataDownNet(final String url, final HttpCallbackListener listener) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder().url(url).build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        final String result = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (listener != null) {
                                        listener.onFinish(result);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    if (listener != null) {
                                        listener.onError(e);
                                    }
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
